package threadTest;

// 有两个用户分别从同一个卡上取钱（总额10000）
// 每次都取1000，当余额不足时就不能取款了
// 不能出现超取现象
public class Homework02 {

    public static void main(String[] args) {
        Customer customer = new Customer();
        Thread thread1 = new Thread(customer);
        thread1.setName("客户1");
        Thread thread2 = new Thread(customer);
        thread2.setName("客户2");
        thread1.start();
        thread2.start();
    }
}

// 如果要共享资源则使用实现接口的方式实现多线程
class Customer implements Runnable{

    private int money = 10000;

    public void run() {
        // 线程同步（加锁）
        synchronized (this){
            while (true){
                if (money < 1000){
                    System.out.println("余额不足,线程结束");
                    break;
                }
                money -= 1000;

                System.out.println("用户：" + Thread.currentThread().getName()+"取了钱，还剩"+money+"元");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}